package com.example.lib_common_ui.base


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<T : ViewBinding> : Fragment() {

    // 使用可空类型避免内存泄漏
    private var _binding: T? = null
    protected val binding: T get() = _binding ?: throw IllegalStateException("Binding is null")

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 初始化绑定
        _binding = initBinding(inflater, container)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initUI(savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理绑定引用，避免内存泄漏
        _binding = null
    }

    protected open fun initUI(savedInstanceState: Bundle?) {
        // 子类可覆盖此方法进行UI初始化
    }

    @Suppress("UNCHECKED_CAST")
    private fun initBinding(inflater: LayoutInflater, container: ViewGroup?): T {
        return try {
            // 获取泛型类型
            val type = (javaClass.genericSuperclass as? ParameterizedType)
                ?: throw IllegalStateException("Missing generic type parameter")

            // 获取绑定类
            val clazz = type.actualTypeArguments[0] as Class<*>

            // 查找inflate方法 (使用三个参数的重载)
            val method = clazz.getDeclaredMethod(
                "inflate",
                LayoutInflater::class.java,
                ViewGroup::class.java,
                Boolean::class.java
            )
            method.invoke(null, inflater, container, false) as T
        } catch (e: Exception) {
            throw IllegalStateException("Binding initialization failed", e)
        }
    }
}